package com.shunda.ysdgj.manager.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shunda.ysdgj.common.exception.CustomException;
import com.shunda.ysdgj.common.util.ValidateUtil;
import com.shunda.ysdgj.manager.mapper.system.SysRoleMenuMapper;
import com.shunda.ysdgj.manager.service.system.SysRoleMenuService;
import com.shunda.ysdgj.model.entity.system.SysRoleMenu;
import com.shunda.ysdgj.model.vo.ResultCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService, IService<SysRoleMenu> {

    public List<Long> getAssignedMenuIds(Long roleId) {
        if (ValidateUtil.isNotLong(roleId)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        return lambdaQuery()
                .eq(SysRoleMenu::getRoleId, roleId)
                .eq(SysRoleMenu::getIsHalf, 0)
                .list().stream().map(SysRoleMenu::getMenuId).toList();
    }

    public List<Long> getAssignedMenuIdsByRoleIds(List<Long> roleIds) {
        if (roleIds.isEmpty()) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        return lambdaQuery()
                .in(SysRoleMenu::getRoleId, roleIds).list()
                .stream().map(SysRoleMenu::getMenuId).toList();
    }

    @Transactional
    public boolean add(List<SysRoleMenu> sysRoleMenuList) {
        if (sysRoleMenuList.isEmpty()) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        Long roleId = sysRoleMenuList.get(0).getRoleId();
        LambdaQueryWrapper<SysRoleMenu> baseWrapper = new LambdaQueryWrapper<>();
        remove(baseWrapper.eq(SysRoleMenu::getRoleId, roleId));
        return saveBatch(sysRoleMenuList);
    }

    // 修改某个菜单的半选状态
    public void modifyMenuHalf(Long menuId, Integer halfValue) {
        if (ValidateUtil.isNotLong(menuId)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setIsHalf(halfValue);
        lambdaUpdate().eq(SysRoleMenu::getMenuId, menuId).update(sysRoleMenu);
    }

}
